package org.springblade.modules.repair.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.common.utils.AsyncHttpUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.repair.dto.RescueNoticeConfirmDTO;
import org.springblade.modules.repair.dto.RescueNoticeListDTO;
import org.springblade.modules.repair.dto.plan.PlanAddUserDTO;
import org.springblade.modules.repair.entity.MaintainPlanContent;
import org.springblade.modules.repair.entity.RescueNotice;
import org.springblade.modules.repair.enums.MaintainPlanContentEnum;
import org.springblade.modules.repair.service.IMaintainMalfunctionRescueService;
import org.springblade.modules.repair.service.IMaintainPlanContentService;
import org.springblade.modules.repair.service.IRescueNoticeService;
import org.springblade.modules.repair.vo.RescueNoticeTitleVO;
import org.springblade.modules.repair.vo.rescue.RescueNoticeDetailVO;
import org.springblade.modules.repair.vo.rescue.RescueNoticeListVO;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 救援通知记录表 控制器
 *
 * @author ysq
 * @since 2023-09-14
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/repair/rescue/notice")
@Api(value = "救援通知记录表", tags = "救援通知记录表接口")
public class RescueNoticeController extends BladeController {

	private final IRescueNoticeService rescueNoticeService;

	private final ProjectApiConfiguration projectApiConfiguration;

	private final IMaintainPlanContentService maintainPlanContentService;

	private final AsyncHttpUtil asyncHttpUtil;

	private final IMaintainMalfunctionRescueService maintainMalfunctionRescueService;

	/**
	 * 2025-07 告警分页列表
	 * 包含：梯联网（物联网AI告警）、AI告警信息列表
	 */
	@PostMapping("/search/list")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "救援告警列表")
	public R<IPage<RescueNoticeListVO>> getNoticeListByCondition(@RequestBody RescueNoticeListDTO rescueNoticeListDTO, @RequestBody Query query) {
		// 工单状态条件组装
		return R.data(rescueNoticeService.getNoticeListByCondition(Condition.getPage(query), rescueNoticeListDTO));
	}

	/**
	 * 根据告警id 获取救援告警详情
	 *
	 * @param rescueNoticeId 告警id
	 * @return RescueNoticeDetailVO 告警结果
	 */
	@GetMapping("/detail/by/id")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "救援告警详情")
	public R<RescueNoticeDetailVO> getNoticeDetail(Long rescueNoticeId) {
		return R.data(rescueNoticeService.getNoticeDetailById(rescueNoticeId));
	}

	/**
	 * 确认救援告警为误报
	 */
	@PostMapping("/confirm")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "确认救援告警")
	public R<String> submit(@RequestBody RescueNoticeConfirmDTO confirmDTO) {
		String body = HttpUtil.createPost(projectApiConfiguration.getWeb() + "/admin/rescue/notice/confirm")
			.header(TokenConstant.HEADER, AuthUtil.getHeader(WebUtil.getRequest()))
			.body(Func.toJson(confirmDTO)).execute(false).body();
		JSONObject resultObject = JSON.parseObject(body);
		if(resultObject.containsKey("msg")){
			if("报警已经确认，无需再确认".equals(resultObject.getString("msg"))){
				throw new ServiceException("报警已经确认，无需再确认");
			}
		}
		if(resultObject.containsKey("data")){
			String successString = resultObject.getString("data");
			if(Func.isBlank(successString)){
				return R.data(null);
			}
			try{
				Long rescuePlanId = Long.valueOf(successString);
				MaintainPlanContent currentRescuePlan = maintainPlanContentService.getById(rescuePlanId);
				if(confirmDTO.getIfSendMyself() && Integer.valueOf(MaintainPlanContentEnum.MAINTAIN_KR.getId()).equals(currentRescuePlan.getTypeStatus())){
					PlanAddUserDTO planAddUserDTO = new PlanAddUserDTO();
					planAddUserDTO.setAddType(1);
					planAddUserDTO.setStatus(1);
					planAddUserDTO.setPlanId(rescuePlanId);
					Long userId = AuthUtil.getUserId();
					List<Long> userIds = new ArrayList<>();
					userIds.add(userId);
					planAddUserDTO.setUserIds(userIds);
					maintainMalfunctionRescueService.planAddUser(planAddUserDTO);
				}
			}catch (Exception e){
				log.error("确认救援告警失败", e);
				throw new ServiceException("确认救援告警失败");
			}
			return R.data(successString);
		}
		return R.data(null);
	}

	/**
	 * 抬头统计
	 */
	@GetMapping("/title/statistics")
	@ApiOperation("分页列表抬头统计")
	@ApiOperationSupport(order = 10)
	public R<Map<String, Integer>> titleStatistics() {
		Map<String, Integer> titleStatistics = new HashMap<>(2);

		List<RescueNoticeTitleVO> titleVOList = rescueNoticeService.countWithRoles();
		if(Func.isEmpty(titleVOList)){
			titleStatistics.put("total", 0);
			titleStatistics.put("unConfirm", 0);
			titleStatistics.put("confirmed", 0);
			return R.data(titleStatistics);
		}

		int total = titleVOList.size();
		long unConfirmLongValue = titleVOList.stream().filter(t -> {
			Long unConfirmedId = t.getUnConfirmedId();
			return !Long.valueOf(-1L).equals(unConfirmedId);
		}).count();
		int unConfirm = (int) unConfirmLongValue;
		int confirmed = total - unConfirm;
		titleStatistics.put("total", total);
		titleStatistics.put("unConfirm", unConfirm);
		titleStatistics.put("confirmed", confirmed);
		return R.data(titleStatistics);
	}
}
